//
//  UIView.swift
//  fho
//
//  Created by 郭颢源 on 2021/3/31.
//

import Foundation
import UIKit

extension UIView {
    
    func showSubviews() {
        for obj in subviews {
//            print("****",obj.description)
            if obj.isKind(of: UIView.self) {
                let hue :CGFloat =  CGFloat(arc4random() % 255) / 255.0 ;  //0.0 to 1.0
                let saturation :CGFloat = CGFloat(arc4random() % 128) / 255.0  + 0.5;  // 0.5 to 1.0,away from white
                let brightness :CGFloat = CGFloat(arc4random_uniform(128)) / 255.0 + 0.5;  //0.5 to 1.0,away from black
                obj.backgroundColor = UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0)
                obj.showSubviews()
            }
        }
    }
    
    private struct AssociatedKeys {
        static var descriptiveName = "AssociatedKeys.DescriptiveName.blurView"
    }
    
    private (set) var blurView: BlurView {
        get {
            if let blurView = objc_getAssociatedObject(
                self,
                &AssociatedKeys.descriptiveName
                ) as? BlurView {
                return blurView
            }
            self.blurView = BlurView(to: self)
            return self.blurView
        }
        set(blurView) {
            objc_setAssociatedObject(
                self,
                &AssociatedKeys.descriptiveName,
                blurView,
                .OBJC_ASSOCIATION_RETAIN_NONATOMIC
            )
        }
    }
    
    class BlurView {
        
        private var superview: UIView
        private var blur: UIVisualEffectView?
        private var editing: Bool = false
        private (set) var blurContentView: UIView?
        private (set) var vibrancyContentView: UIView?
        
        var animationDuration: TimeInterval = 0.1
        
        /**
         * Blur style. After it is changed all subviews on
         * blurContentView & vibrancyContentView will be deleted.
         */
        var style: UIBlurEffect.Style = .light {
            didSet {
                guard oldValue != style,
                    !editing else { return }
                applyBlurEffect()
            }
        }
        /**
         * Alpha component of view. It can be changed freely.
         */
        var alpha: CGFloat = 0 {
            didSet {
                guard !editing else { return }
                if blur == nil {
                    applyBlurEffect()
                }
                let alpha = self.alpha
                UIView.animate(withDuration: animationDuration) {
                    self.blur?.alpha = alpha
                }
            }
        }
        
        init(to view: UIView) {
            self.superview = view
        }
        
        func setup(style: UIBlurEffect.Style, alpha: CGFloat) -> Self {
            self.editing = true
            
            self.style = style
            self.alpha = alpha
            
            self.editing = false
            
            return self
        }
        
        func enable(isHidden: Bool = false) {
            if blur == nil {
                applyBlurEffect()
            }
            
            self.blur?.isHidden = isHidden
        }
        
        private func applyBlurEffect() {
            blur?.removeFromSuperview()
            
            applyBlurEffect(
                style: style,
                blurAlpha: alpha
            )
        }
        
        private func applyBlurEffect(style: UIBlurEffect.Style,
                                     blurAlpha: CGFloat) {
            superview.backgroundColor = UIColor.clear
            
            let blurEffect = UIBlurEffect(style: style)
            let blurEffectView = UIVisualEffectView(effect: blurEffect)
            
            let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
            let vibrancyView = UIVisualEffectView(effect: vibrancyEffect)
            blurEffectView.contentView.addSubview(vibrancyView)
            
            blurEffectView.alpha = blurAlpha
            
            superview.insertSubview(blurEffectView, at: 0)
            
            blurEffectView.addAlignedConstrains()
            vibrancyView.addAlignedConstrains()
            
            self.blur = blurEffectView
            self.blurContentView = blurEffectView.contentView
            self.vibrancyContentView = vibrancyView.contentView
        }
    }
    
    private func addAlignedConstrains() {
        translatesAutoresizingMaskIntoConstraints = false
        addAlignConstraintToSuperview(attribute: NSLayoutConstraint.Attribute.top)
        addAlignConstraintToSuperview(attribute: NSLayoutConstraint.Attribute.leading)
        addAlignConstraintToSuperview(attribute: NSLayoutConstraint.Attribute.trailing)
        addAlignConstraintToSuperview(attribute: NSLayoutConstraint.Attribute.bottom)
    }
    
    private func addAlignConstraintToSuperview(attribute: NSLayoutConstraint.Attribute) {
        superview?.addConstraint(
            NSLayoutConstraint(
                item: self,
                attribute: attribute,
                relatedBy: NSLayoutConstraint.Relation.equal,
                toItem: superview,
                attribute: attribute,
                multiplier: 1,
                constant: 0
            )
        )
    }
    ///
    /// 从Nib加载视图
    ///
    /// Nibname doesn't need to be passed, If empty, the caller's own name
    ///
    /// - parameter nibName: Nib View name, can be empty
    ///
    /// - returns: View loaded from Nib
    ///
    class func sg_loadFromNib(_ nibName: String? = nil) -> UIView {
        let name = nibName == nil ? "\(self)" : nibName!
        return Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as! UIView
    }
    
    ///
    /// Gets the controller where the current view is located
    ///
    /// - returns: The controller where the current view is located
    ///
    func sg_getController() -> UIViewController? {
        var nextResponder: UIResponder? = self.next
        repeat {
            nextResponder = nextResponder?.next
            if let viewController = nextResponder as? UIViewController {
                return viewController
            }
        } while nextResponder != nil
        return nil
    }
    
    /// 向窗口添加视图
    func sg_addToKeyWindow() {
        UIApplication.shared.windows.first?.addSubview(self)
    }
    
    /// 删除视图上的所有子视图
    func sg_removeAllSubviews() {
        for tempSubviews in self.subviews {
            print(tempSubviews);
            tempSubviews.removeFromSuperview()
        }
    }
    ///
    /// 删除视图上具有指定类名的子视图
    ///
    /// - parameter aClass: Remove the specified class
    ///
    func sg_removeAllSubviewsIsMember(of aClass: AnyClass) {
        for tempSubView in self.subviews {
            if tempSubView.isMember(of: aClass) {
                tempSubView.removeFromSuperview()
            }
        }
    }
    
    ///
    /// 添加圆角
    ///
    /// 使用图层添加圆角到视图
    ///
    /// - parameter radius: Corner size
    ///
    func sg_addCorner(radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.masksToBounds = true
    }
    
    /// 设置圆角
    /// - Parameter radius: 角度
    func set_cornerRadius(radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.masksToBounds = true
    }
    ///
    /// 添加圆角
    ///
    /// 使用UIBezierPath和CAShapeLayer为视图添加圆角
    ///
    /// - parameter radius: Corner size
    /// - parameter direction: Corner direction
    ///
    func sg_addCorner(radius: CGFloat, direction: UIRectCorner) {
        let bezierPath = UIBezierPath.init(roundedRect: self.bounds, byRoundingCorners: direction, cornerRadii: CGSize.init(width: radius, height: radius))
        let shapeLayer = CAShapeLayer.init()
        shapeLayer.frame = self.bounds
        shapeLayer.path = bezierPath.cgPath
        self.layer.mask = shapeLayer
        
//        let borderLayer = CAShapeLayer()
//        borderLayer.path = shapeLayer.path // Reuse the Bezier path
//        borderLayer.fillColor = UIColor.clear.cgColor
//        borderLayer.strokeColor = UIColor.green.cgColor
//                borderLayer.lineWidth = 5
//                borderLayer.frame = self.bounds
//        self.layer.addSublayer(borderLayer)

    }
    ///
    /// 添加边框宽度和边框颜色
    ///
    /// 使用图层添加边框宽度和边框颜色
    ///
    /// - parameter width: Border width
    /// - parameter color: Border color
    ///
    func sg_addLayerBorder(width: CGFloat, color: UIColor) {
        self.layer.borderWidth = width
        self.layer.borderColor = color.cgColor

        }
    
    ///
    /// 给视图添加阴影
    ///
    /// - parameter color: ShadowColor
    /// - parameter offset: ShadowOffset
    /// - parameter radius: ShadowRadius
    ///
    func sg_addShadow(color: UIColor, offset: CGSize, radius: CGFloat) {
        self.layer.shadowColor = color.cgColor
        self.layer.shadowOffset = offset
        self.layer.shadowRadius = radius
        self.layer.shadowOpacity = 1.0
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = UIScreen.main.scale
    }
    
    
}

